/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2023-05-04
 * Time: 10:41
 */

//服务器负载均衡(Load Balance)软件
import java.util.ArrayList;
import java.util.Random;
public class LoadBalancer
{
    // 私有静态变量，存储唯一实例
    private static LoadBalancer instance = null;
    // 服务器集合
    private ArrayList<CustomService> serverList = null;
    // 私有构造函数
    private LoadBalancer()
    {
        serverList = new ArrayList<CustomService>();
    }
    // 公共静态成员方法，返回唯一实例
    public static LoadBalancer GetLoadBalancer() {
        if (instance == null) {
            instance = new LoadBalancer();
        }
        return instance;
    }
    // 添加一台Server
    public void AddServer(CustomService server)
    {
        serverList.add(server);
    }
    // 移除一台Server
    public void RemoveServer(String serverName)
    {
        for(CustomService server:serverList){
            if (server.Name.equals(serverName))
            {
                serverList.remove(server);
                break;
            }
        }
    }
    // 获得一台Server - 使用随机数获取
    private Random rand = new Random();
    public CustomService GetServer()
    {
        int index=rand.nextInt(serverList.size());
        return serverList.get(index);
    }
}

